package com.campusflea.person;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.campusflea.DateBase.ShopInfo;
import com.campusflea.DateBase.UserInfo;
import com.campusflea.R;
import com.campusflea.ReleaseActivity;
import com.campusflea.utils.PathGetter;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

import static io.rong.imkit.plugin.image.PictureSelectorActivity.REQUEST_CODE_ASK_PERMISSIONS;

/**
 * Created by Administrator on 2017/6/10.
 */

public class Person_infor extends Activity implements View.OnClickListener{
    protected Context mContext;
    private BottomMenuDialog dialog;
    private PhotoUtils photoUtils;
    private ImageView image;
    private Uri uri;
    private Button btn_hui;
    private UserInfo userInfo;
    private static final String IMAGE_FILE_NAME = "faceImage.jpg";
    private TextView tv_my_username,tv_my_phone;
//    public Person_infor(UserInfo userInfo){
//        this.userInfo=userInfo;
//    }
//    public Person_infor(){
//
//    }
    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail_infor);
        btn_hui= (Button) findViewById(R.id.button7);
        btn_hui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mContext=this;
        TextView mPhone = (TextView) findViewById(R.id.tv_my_phone);
        RelativeLayout portraitItem = (RelativeLayout) findViewById(R.id.rl_my_portrait);
        RelativeLayout nameItem = (RelativeLayout) findViewById(R.id.rl_my_username);
        image= (ImageView) findViewById(R.id.imageView2);
        Intent intent = getIntent();
        userInfo=(UserInfo)intent.getSerializableExtra("ui");
        tv_my_username= (TextView) findViewById(R.id.tv_my_username);
        tv_my_phone= (TextView) findViewById(R.id.tv_my_phone);
        tv_my_username.setText(userInfo.getNickname().toString());
        tv_my_phone.setText(userInfo.getPhone().toString());
        if(userInfo.getImage()!=null){

            Bitmap bitmap=getHttpBitmap(userInfo.getImage().getFileUrl());
            image.setImageBitmap(bitmap);
        }
        portraitItem.setOnClickListener(this);
        nameItem.setOnClickListener(this);

    }

    public Bitmap getHttpBitmap(String url){
        Bitmap bitmap=null;
        URL myUrl;

        try {
            myUrl=new URL(url);
            HttpURLConnection conn=(HttpURLConnection)myUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.connect();
            InputStream is=conn.getInputStream();
            bitmap= BitmapFactory.decodeStream(is);
            is.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //返回圆形bitmap
        return bitmap;
    }
    private void showPhotoDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }

        dialog = new BottomMenuDialog(mContext);
        dialog.setConfirmListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                if (Build.VERSION.SDK_INT >= 23) {
                    int checkPermission = checkSelfPermission(Manifest.permission.CAMERA);
                    if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                        if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
                            requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_ASK_PERMISSIONS);
                        } else {
                            new AlertDialog.Builder(mContext)
                                    .setMessage("您需要在设置里打开相机权限。")
                                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            //最好用try/catch包裹一下，防止因为用户未给应用程序开启相机权限，而使程序崩溃
                                            try {
                                                Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//开启相机应用程序获取并返回图片（capture：俘获）
                                                intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                                                        "head.jpg")));//指明存储图片或视频的地址URI
                                                startActivityForResult(intent2, 0x100);//采用ForResult打开
                                            } catch (Exception e) {
                                                Toast.makeText(Person_infor.this, "相机无法启动，请先开启相机权限", Toast.LENGTH_LONG).show();
                                            }
                                        }
                                    })
                                    .setNegativeButton("取消", null)
                                    .create().show();
                        }
                        return;
                    }
                }
                photoUtils.takePicture(Person_infor.this);
            }
        });
        dialog.setMiddleListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (dialog != null && dialog.isShowing()) {
                    Toast.makeText(Person_infor.this,"111111"+222,Toast.LENGTH_SHORT).show();

                            Intent intent = new Intent(Intent.ACTION_PICK, null);
                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                    "image/*");
                            startActivityForResult(intent, 0x1);

                }

            }
        });
        dialog.show();
    }
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (requestCode == 0x1 && resultCode == RESULT_OK) {
            if (data != null) {
                uri=data.getData();
                //Picasso.with(Person_infor.this).load(uri).resize(64,64).into(image);
                image.setImageURI(uri);
                dialog.dismiss();
                File file = new File(PathGetter.getPath(Person_infor.this, uri));
                final BmobFile bmobFile = new BmobFile(file);
                Toast.makeText(Person_infor.this,PathGetter.getPath(Person_infor.this, uri),Toast.LENGTH_LONG).show();                //Toast.makeText(ReleaseActivity.this,bmobFile.toString(),Toast.LENGTH_LONG).show();

                bmobFile.uploadblock(new UploadFileListener() {
                    @Override
                    public void done(BmobException e) {

                        userInfo.setImage(bmobFile);
//                        userInfo.save(new SaveListener<String>() {
//                            @Override
//                            public void done(String s, BmobException e) {
//                                Toast.makeText(Person_infor.this, "上传成功", Toast.LENGTH_SHORT).show();
//                            }
//                        });
                        userInfo.update(userInfo.getObjectId(), new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                Toast.makeText(Person_infor.this, "修改成功！", Toast.LENGTH_SHORT).show();

                            }
                        });
                    }

//                    @Override
//                    public void done(BmobException e) {
//                        ShopInfo shopInfo = new ShopInfo();
//                        shopInfo.setBmobFile(bmobFile);
//                        shopInfo.save(new SaveListener() {
//                            @Override
//                            public void done(Object o, Object o2) {
//
//                            }
//
//                            @Override
//                            public void done(Object o, BmobException e) {
//                                Toast.makeText(Person_infor.this,"发布成功",Toast.LENGTH_LONG).show();
//                            }
//                        });
//                        Toast.makeText(Person_infor.this, "上传成功", Toast.LENGTH_SHORT).show();
//                    }

                });
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x100 && resultCode == RESULT_OK){
            File temp = new File(Environment.getExternalStorageDirectory()
                    + "/head.jpg");
            cropPhoto(Uri.fromFile(temp));//裁剪图片
        }
    }

    //裁剪图片
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        //找到指定URI对应的资源图片

        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 500);
        intent.putExtra("outputY", 500);
        intent.putExtra("return-data", true);
        //进入系统裁剪图片的界面
        try{
            startActivityForResult(intent, 3);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_my_portrait:
                showPhotoDialog();
//                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                startActivityForResult(intent, 1);
                break;
            case R.id.rl_my_username:
                startActivity(new Intent(this, Person_Name.class));
                break;
            case R.id.rl_my_telephone:
//                Toast.makeText(this,"--------------",Toast.LENGTH_SHORT).show();
                startActivity(new Intent(this, Person_phone.class));
                break;

        }
    }
}
